package com.caimiao.miao.library.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.caimiao.miao.bean.TicketOut;

import java.util.ArrayList;
import java.util.List;

public abstract class DBHelperImpl<T> implements IDBHelper<T> {
    protected SQLiteDatabase db;

    protected abstract String getTableName();

    public DBHelperImpl() {
        db = SQLiteDBHelper.getInstance().getWritableDatabase();
    }

    @Override
    public void backup(List<T> dataList) {
        if (dataList == null || dataList.isEmpty())
            return;
        db.beginTransaction();
        try {
            for (int i = 0; i < dataList.size(); i++) {
                insert(dataList.get(i));
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    @Override
    public long insert(T data) {
        return db.insert(getTableName(), null, get(data));
    }

    @Override
    public int update(ContentValues values, String clause, String[] args) {
        return db.update(getTableName(), values, clause, args);
    }

    @Override
    public void delete(String clause, String[] args) {
        db.delete(getTableName(), clause, args);
    }

    @Override
    public List<T> getAll() {
        List<T> dataList = new ArrayList<>();
        Cursor cursor = db.query(getTableName(), null, null, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                dataList.add(get(cursor));
            }
            cursor.close();
        }
        return dataList;
    }

    @Override
    public boolean has(String clause, String[] args) {
        boolean ret = false;
        Cursor cursor = db.query(getTableName(), null, clause, args, null, null, null);
        if (cursor != null) {
            ret = cursor.moveToFirst();
            cursor.close();
        }
        return ret;
    }
}
